import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/sub/SessionGroupSettingPage.dart';
import 'package:im_app/im/page/sub/SessionUserSettingPage.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:im_app/im/page/view/component/GroupIconView.dart';
import 'package:im_app/im/util/DbUtil.dart';
import 'package:im_app/im/util/ImConstant.dart';
import 'package:im_app/im/util/UiUtil.dart';

import '../../dao/ImGroupDao.dart';
import '../../dao/ImSessionDao.dart';
import '../../pojo/ImPojo.dart';
import '../../socket/dto/business/SendData.dart';
import '../../socket/service/RpcSendDataService.dart';
import '../bloc/SessionListCubit.dart';
import '../bloc/SessionSettingCubit.dart';
import '../view/component/SessionIconView.dart';

/// 修改群介绍
class GroupChangeDescriptionPage extends StatefulWidget {
  final ImSession session;

  const GroupChangeDescriptionPage({required this.session, super.key});

  @override
  State<StatefulWidget> createState() => _ChangeGroupNameState();
}

class _ChangeGroupNameState extends State<GroupChangeDescriptionPage> {
  var _groupDescription = '';
  late TextEditingController _editingController;

  @override
  void initState() {
    super.initState();

    _editingController = TextEditingController();
    _editingController.text = widget.session.group?.description??'';
    setState(() {
      _groupDescription = widget.session.group?.description??'';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      backgroundColor: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      body: _buildBody(context),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      backgroundColor: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      title: const Text('群公告', style: TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE),),
      centerTitle: true,
      leading: GestureDetector(
        child: const Icon(Icons.chevron_left),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  Widget _buildBody(BuildContext context) {
    return Center(
      child: Container(
        height: 500,
        margin: const EdgeInsets.only(left: 10, right: 10),
        child: Column(
          children: [
            const Text(
              "修改群公告",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
            ),
            const Padding(
              padding: EdgeInsets.only(top: 10, bottom: 20),
              child: Text("修改群公告后，将在群内通知其他成员。"),
            ),
            ListSeparator(
              indent: 20,
              endIndent: 20,
            ),
            Row(
              children: [
                Padding(padding: const EdgeInsets.only(right: 10), child: SessionIconView(session: widget.session),),
                Expanded(
                  child: TextField(
                    controller: _editingController,
                    style: const TextStyle(fontSize: ImConstant.IM_SMALL_SIZE),
                    maxLines: 3,
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      hintText: '请输入内容',
                    ),
                    onChanged: (value) => _groupDescription = value,
                  ),
                ),
                Visibility(
                  replacement: const SizedBox(width: 18.0,),
                  visible: _groupDescription != '',
                  child: IconButton(
                    icon: const Icon(Icons.cancel),
                    color: Colors.grey,
                    hoverColor: Colors.white,
                    iconSize: 18.0,
                    onPressed: () {
                      _editingController.clear();
                      _groupDescription = '';
                    },
                  ),
                )
              ],
            ),
            ListSeparator(
              indent: 20,
              endIndent: 20,
            ),
            const SizedBox(height: 200,),
            SizedBox(width: 120, child: FilledButton(
                style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.green)),
                onPressed: _submit,
                child: const Text('完成', style: TextStyle(color: Colors.white))
            ),),
          ],
        ),
      ),
    );
  }

  void _submit() async {
    if (_groupDescription != '') {
      if (_groupDescription.length > ImConstant.IM_GROUP_DESCRIPTION_LENGTH) {
        showModalBottomSheet(
            context: context,
            builder: (context) {
              return const Text('群描述太长，不能超过${ImConstant.IM_GROUP_DESCRIPTION_LENGTH}字');
            });
        return;
      }
      var imGroup = widget.session.group!;
      imGroup.description = _groupDescription;
      imGroup.updateTime = DateTime.now();

      RpcMessageService rpcMessageService = RpcMessageService();
      DataChangeReq dataChangeReq = DataChangeReq(type: DataType.group, subType: DataSubType.g_ed_desc,
          key: imGroup.code, value: _groupDescription);
      rpcMessageService.sendDataChange(dataChangeReq);

      var imGroupDao = ImGroupDao();
      imGroupDao.batchUpdates([imGroup]);

      widget.session.group = imGroup;

      var sessionListCubit = context.read<SessionListCubit>();
      Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) {
        return BlocProvider(
          create: (context) => SessionSettingCubit(session: widget.session, sessionListCubit: sessionListCubit),
          child: const SessionGroupSettingPage(),
        );
      }), ModalRoute.withName("/MessageSendPage"));
    } else {
      showModalBottomSheet(
          context: context,
          builder: (context) {
            return const Text('群描述不能为空');
          });
    }
  }
}
